package com.cloud.actuator.config;

import jakarta.servlet.DispatcherType;
import lombok.RequiredArgsConstructor;
import de.codecentric.boot.admin.server.config.AdminServerProperties;
import lombok.SneakyThrows;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration(proxyBeanMethods = false)
@RequiredArgsConstructor
public class SecuritySecureConfig {

    private final AdminServerProperties adminServer;
    private final SecurityProperties security;


    @SneakyThrows
    @Bean
    protected SecurityFilterChain filterChain(HttpSecurity http){
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setTargetUrlParameter("redirectTo");
        successHandler.setDefaultTargetUrl(this.adminServer.path("/"));

        http.authorizeHttpRequests(authorizeHttpRequests->{
            authorizeHttpRequests
                    .requestMatchers(new AntPathRequestMatcher(this.adminServer.path("/assets/**"))).permitAll()
                    .requestMatchers(new AntPathRequestMatcher(this.adminServer.path("/actuator/*"))).permitAll()
                    .requestMatchers(new AntPathRequestMatcher(this.adminServer.path("/login"))).permitAll()
                    .dispatcherTypeMatchers(DispatcherType.ASYNC).permitAll()
                    .anyRequest().authenticated();
        }).formLogin((formLogin) -> formLogin.loginPage(this.adminServer.path("/login")).successHandler(successHandler))
          .logout((logout) -> logout.logoutUrl(this.adminServer.path("/logout")))
          .csrf(csrf->csrf.disable())
          .httpBasic(Customizer.withDefaults())
        ;
        return http.build();
    }

}
